﻿#include "grid.h"
#include "screen.h"
#include "tiplist.h"
#include "cmath"
#include <QGraphicsSceneContextMenuEvent>
#include <QMenu>
#include <QAction>
#include <QVBoxLayout>
#include <QVariant>

EditGrid::EditGrid(EditScreen* parent) :
    Grid((Screen*) parent)
{
    p = parent;
    state = false;
    R = 0;
    G = 0;
    B = 0;
    connect(parent->buttonDone, SIGNAL(clicked()), this, SLOT(SaveGrid()));
    connect(parent->buttonSave, SIGNAL(clicked()), this, SLOT(SaveDraft()));
}
//Can xu ly truong hop de trung !!!
void EditGrid::contextMenuEvent(QGraphicsSceneContextMenuEvent *event)
{
    int tempX = floor(event->scenePos().x()/50);
    int tempY = floor(event->scenePos().y()/50);
    int key = 1+tempX+tempY*10;

    QMenu menu;
    QAction* actionRange = menu.addAction(QString::fromUtf8("Chọn Vùng Từ"));
    QAction* actionRangeQuit = menu.addAction(QString::fromUtf8("Hủy"));
    QAction* actionUpdate = menu.addAction(QString::fromUtf8("Cập nhật gợi ý Từ"));
    QAction* actionDelete = menu.addAction(QString::fromUtf8("Xóa Ký tự"));
    QAction* actionDeleteWord = menu.addAction(QString::fromUtf8("Xóa Từ"));
    if(state || !cells.contains(key))
        actionUpdate->setDisabled(true);

    if(!state)
        actionRangeQuit->setDisabled(true);

    if(!cells.contains(key))
    {
        actionDelete->setDisabled(true);
        actionDeleteWord->setDisabled(true);
    }

    QAction* actionSelected = menu.exec(event->screenPos());

    if(actionSelected == actionUpdate)
    {
        updateTip(tempX, tempY);
        return;
    }

    if(actionSelected == actionDelete)
    {
        cells[key]->~Cell();
        cells.remove(key);
        return;
    }

    if(actionSelected == actionDeleteWord)
    {
        //
        int tipkey = cells[key]->tips.last();
        QMapIterator<int, Cell*> i(cells);
        while (i.hasNext())
        {
            i.next();
            if(i.value()->tips.indexOf(tipkey) >= 0)
            {
                if(i.value()->tips.size() > 1)
                {
                        i.value()->tips.removeOne(tipkey);
                } else {
                    i.value()->~Cell();
                    cells.remove(i.key());
                }
            }

        }
        Tips.remove(tipkey);
        return;
    }
    if(!state)
    {
        if(actionSelected == actionRange)
        {
            QPen pen;
            QBrush brush;
            pen.setWidth(50);
            brush.setStyle(Qt::Dense6Pattern);
            brush.setColor(Qt::black);
            pen.setBrush(brush);
            startX = tempX;
            startY = tempY;

            //begin of the selection
            vLine = new QGraphicsLineItem(startX*50.0+25.0, 25.0, startX*50.0+25.0, 475.0);
            vLine->setPen(pen);
            addItem(vLine);
            hLine = new QGraphicsLineItem(25.0,startY*50.0+25.0, 475.0, startY*50.0+25.0);
            hLine->setPen(pen);
            addItem(hLine);
            state = true;
        }
    }else{
        hLine->~QGraphicsLineItem();
        vLine->~QGraphicsLineItem();
        state = false;

        if(actionSelected == actionRangeQuit) return;

        if(startX != tempX && startY != tempY){
            QMessageBox msgBox;
            msgBox.setIcon(QMessageBox::Warning);
            msgBox.setText(QString::fromUtf8("Chọn vùng trong phạm vi được đánh dấu."));
            msgBox.exec();
            return;
        }
        QInputDialog inputTip;
        inputTip.setInputMode(QInputDialog::TextInput);
        inputTip.exec();

        if(B <= 207)
        {
            B = B + 48;
        } else if (G <= 207) {
            G = G + 48;
        } else if (R <= 207) {
            R = R + 48;
        } else {
            R = 0;
            G = 0;
            B = 0;
        }

        if(startX == tempX)
        {
            QString str = QString(QString::fromUtf8("Hàng dọc từ %1 tới %2: ").arg(1+startX+startY*10).arg(key) +
                                       inputTip.textValue());
            Tips.insert(Tips.size() + 1, str);

            if(startY < tempY){
                for(int i = startY;  i <= tempY; i++)
                {
                    showCell(startX, i);
                }
            }else{
                for(int i = tempY;  i <= startY; i++)
                {
                    showCell(startX, i);
                }
            }
        }else if(startY == tempY){
            QString str = QString(QString::fromUtf8("Hàng ngang từ %1 tới %2: ").arg(1+startX+startY*10).arg(key) +
                                       inputTip.textValue());
            Tips.insert(Tips.size() + 1, str);

            if(startX < tempX){
                for(int i = startX;  i <= tempX; i++)
                {
                    showCell(i, startY);
                }
            }else{
                for(int i = tempX;  i <= startX; i++)
                {
                    showCell(i, startY);
                }
            }
        }
    }
}

void EditGrid::showCell(int X, int Y)
{
    QColor color(R, G, B, 140);
    int key = 1+X+Y*10;
    if(cells.contains(key))
    {
        cells[key]->tips.append(Tips.size());
    } else {
        Cell* w = new Cell(X*50, Y*50, color);
        w->tips.append(Tips.size());
        cells.insert(key, w);
        addItem(w->rect);
        addItem(w->cap);
    }
}

void EditGrid::updateTip(int X, int Y)
{
    int key = 1+X+Y*10;
    QDialog* update = new QDialog();
    update->setAttribute(Qt::WA_DeleteOnClose);

    QVBoxLayout* layout = new QVBoxLayout(update);

    QLabel* label = new QLabel(QString::fromUtf8("Cập nhật danh sách các gợi ý của ô.\n").append(
                                   QString::fromUtf8("1. Click vào gợi ý muốn sửa.\n")).append(
                                   QString::fromUtf8("Lưu ý: (1) sẽ cập nhật tất cả các ô dùng chung gợi ý.\n")).append(
                                   QString::fromUtf8("2. Chọn một gợi ý để thêm vào danh sách.\n")).append(
                                   QString::fromUtf8("3. Click xóa thể loại bỏ 1 gợi ý ra khỏi ô.\n")).append(
                                   QString::fromUtf8("Lưu ý: (2) và (3) chỉ có tác dụng cho ô đang hiện hành\n")), update);
    layout->addWidget(label);


    for(int i = 0; i < cells[key]->tips.size(); i++)
    {
        QHBoxLayout* hlayout = new QHBoxLayout();

        QLabel* label = new QLabel(QString("<a href='%1'>").arg(cells[key]->tips[i]).append(Tips[cells[key]->tips[i]]).append("</a>"), update);
        connect(label, SIGNAL(linkActivated(QString)), this, SLOT(updateTipSlot(QString)));

        QLabel* dellabel = new QLabel(QString(" <a href='%1|%2'>").arg(key).arg(i).append("(X)</a>"), update);
        connect(dellabel, SIGNAL(linkActivated(QString)), this, SLOT(deleteTipSlot(QString)));

        hlayout->addWidget(label);
        hlayout->addWidget(dellabel);
        layout->addLayout(hlayout);
    }

    TipList* tiplist = new TipList(update);
    tiplist->key = key;
    QMapIterator<int, QString> j(Tips);
    while (j.hasNext())
    {
        j.next();
        for(int i = 0; i < cells[key]->tips.size(); i++)
        {
            if(cells[key]->tips.indexOf(j.key()) == -1)
                tiplist->box->addItem(j.value(), QVariant(j.key()));
        }
    }

    layout->addWidget(tiplist->box);
    layout->addWidget(tiplist->button);

    if(tiplist->box->count() < 1)
    {
        tiplist->box->hide();
        tiplist->button->hide();
    }
    connect(tiplist,SIGNAL(updatedTip(int,int)), this, SLOT(addTipSlot(int, int)));

    QPushButton* ok = new QPushButton("OK", update);
    connect(ok, SIGNAL(clicked()), update, SLOT(deleteLater()));
    layout->addWidget(ok);

    update->setMinimumSize(450, 300);
    update->setLayout(layout);
    update->exec();
}
void EditGrid::updateTipSlot(QString str)
{
    QInputDialog inputTip;
    inputTip.setInputMode(QInputDialog::TextInput);
    inputTip.setTextValue(Tips.value(str.toInt()));
    inputTip.exec();
    Tips.insert(str.toInt(), inputTip.textValue());
    this->sender()->parent()->deleteLater();
}
void EditGrid::deleteTipSlot(QString str)
{
    QStringList list = str.split("|");
    cells.value(list.value(0).toInt())->tips.removeAt(list.value(1).toInt());
    this->sender()->parent()->deleteLater();
}
void EditGrid::addTipSlot(int key, int i)
{
    cells[key]->tips.append(i);
    this->sender()->parent()->deleteLater();
}

void EditGrid::SaveGrid()
{
    if(cells.size() < 1) return;

    QMapIterator<int, Cell*> i(cells);
    while (i.hasNext())
    {
        i.next();
        if(i.value()->cap->toPlainText() == NULL)
        {
            QMessageBox msgBox;
            msgBox.setIcon(QMessageBox::Warning);
            msgBox.setText(QString::fromUtf8("Còn một số từ còn thiếu ký tự, có lẽ bạn muốn Lưu Nháp."));
            msgBox.exec();
            return;
        }
    }
    Save(0, p->inputName->text());
}

void EditGrid::SaveDraft()
{
    if(cells.size() < 1) return;
    Save(1, p->inputName->text());
}

